'use strict';

const {Service} = require('ee-core');
const util = require('util');
const path = require('path');
const fs = require('fs');
const axios = require("axios")
const {v4: uuidv4} = require('uuid');
const execAsync = util.promisify(require('child_process').exec);
const Log = require('ee-core/log');
const Ps = require('ee-core/ps');
const TaskQueue = require('../utils/queue')


/**
 * 远程请求接口
 * @type {{updatePublishStatus: string, getPublishData: string}}
 */
const request = {
    getPublishData:"https://api.zhijian6.cn/media/publishRecord/getAccountPublishData/",
    updatePublishStatus:'https://api.zhijian6.cn/media/publishRecord/updatePublishStatus'
}

/**
 * 定义请求接口
 * return String
 */
const ChannelsApi = {

    applyuploaddfs: "https://finder-assistant.mp.video.tencent-cloud.com/applyuploaddfs",
    //上传片段
    uploadpartdfs: "https://finder-assistant.mp.video.tencent-cloud.com/uploadpartdfs?",
    //获取个人信息
    helper_upload_params: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/helper/helper_upload_params",
    //合并视频
    completepartuploaddfs: 'https://finder-assistant.mp.video.tencent-cloud.com/completepartuploaddfs?UploadID=',
    //获取clipKey,draftId
    post_clip_video: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/post/post_clip_video",
    //发布视频
    post_create: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/post/post_create",
    //cd结果
    post_clip_video_result: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/post/post_clip_video_result",
    //获取GZH标题
    helper_parse_mp_link: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/helper/helper_parse_mp_link",
    auth_set_finder: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_set_finder",
    //删除视频
    post_delete:'https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/post/post_delete',
    //获取扩展链接链接
    getMpLink:'https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/helper/helper_parse_mp_link',
    //获取草稿箱列表
    getDraftList:'https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/post/get_draft_list'
}


/**
 * 文件操作插件
 * @class
 */
class FfmpegAddon {

    constructor() {
        this.outpathPicture = path.resolve(Ps.getExtraResourcesDir(), './common/picture');
        this.outpathVideo = path.resolve(Ps.getExtraResourcesDir(), './common/video');
        this.ffmpeg = path.resolve(Ps.getExtraResourcesDir(), 'ffmpeg');
        this.pathDir = [this.outpathPicture, this.outpathVideo]
        this.init()
    }

    async mkdirp(dir) {
        const absolutePath = path.resolve(dir);
        try {
            await fs.mkdir(absolutePath, {recursive: true});
        } catch (error) {
            throw new Error('Error creating directory: ' + error);
        }
    }


    async init() {
        try {
            await this.pathDir.forEach(async item => {
                return !fs.existsSync(item) ? await fs.mkdirSync(item, {recursive: true}) : null
            })
        } catch (error) {
            throw new Error('Error initializing: ' + error);
        }
    }


    //删除目录
    async rmdirAsync(dir) {
        try {
            await fs.rmdir(dir, {recursive: true});
        } catch (error) {
            throw new Error('Error removing directory: ' + error);
        }
    }

    async execAsync(command) {
        try {
            const {stdout, stderr} = await execAsync(`${ this.ffmpeg } ${command}`);
            return stdout || stderr;
        } catch (error) {
            return error.message;
        }
    }

    /**获取视频的长宽秒*/
    async durationAndSecond(pathName) {
        try {
            const duration = await this.execAsync(`-i "${pathName}"`);
            const durationCount = /Duration: (.*?),/.exec(duration);
            const Wh = /(\d+){3,4}x(\d+){3,4}/.exec(duration);
            if (Wh && durationCount) {
                const [width, height] = Wh[0].split('x');
                const second = durationCount[1].split(':');
                return {
                    duration: Number((second[2] + second[1] * 60 + second[0] * 60 * 60)).toFixed(2),
                    width,
                    height
                };
            } else {
                throw new Error('Invalid duration or size');
            }
        } catch (error) {
            throw new Error('Error getting duration and size: ' + error);
        }
    }

    async coverAndduration(pathName) {
        try {
            const fileJag = path.resolve(this.outpathPicture, `${String(+new Date())}.jpeg`);
            const {width, height, duration} = await this.durationAndSecond(pathName);
            const left = Number(width) > Number(height) ? Number(width) : Number(height)
            const right = Number(width) < Number(height) ? Number(width) : Number(height)
            await this.execAsync(` -i "${pathName}" -ss 00:00:02 -frames:v 1 -s ${left}x${right}  "${fileJag}"`);
            // await this.execAsync(`-y -i "${pathName}" -f image2 -ss 00:00:01 -vframes 1 -s ${width}*${height} "${fileJag}");
            return {fileJag, width: Number(width), height: Number(height), duration: duration};
        } catch (error) {
            throw new Error('Error generating cover: ' + error);
        }
    }
}



/**
 * media（service层为单例）
 * @class
 */
class MediaService extends Service {

    constructor(ctx) {
        super(ctx);
        this.taskQueue = new TaskQueue();
        this.headers = {
            "Content-Type": "application/json",
            // "Host":"channels.weixin.qq.com",
            // "Referer": "https://channels.weixin.qq.com/",
            "Origin": "https://channels.weixin.qq.com",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"
        }
    }

    /**
     * 读取文件大小
     * */
    async readBigFile(filePath) {
        const stat = await fs.promises.stat(filePath); // 获取文件信息
        const fileSize = stat.size; // 文件总大小
        const chunkSize = 8 * 1024 * 1024; // 切片大小为8M
        const chunkCount = Math.ceil(fileSize / chunkSize); // 切片个数
        const chunks = []; // 切片数组
        for (let i = 0; i < chunkCount; i++) {
            const start = i * chunkSize;
            const end = Math.min(start + chunkSize - 1, fileSize - 1);
            const chunk = await this.readChunk(filePath, start, end);
            chunks.push(chunk);
        }

        return {chunks, fileSize};
    }

    /**
     * 删除文件
     * */

    async remove_file(filePath) {
        try {
            fs.unlinkSync(filePath);
            console.log(`${filePath}删除成功`);
        } catch (error) {
            console.log(`删除${filePath}失败：${error}`);
        }
    }

    /**
     *大文件切片
     */
    async readChunk(filePath, start, end) {
        return new Promise((resolve, reject) => {
            const readStream = fs.createReadStream(filePath, {start, end});
            const chunks = [];
            readStream.on('data', (chunk) => {
                chunks.push(chunk);
            });
            readStream.on('error', (err) => {
                reject(err);
            });
            readStream.on('end', () => {
                resolve(Buffer.concat(chunks));
            });
        });
    }

    async helper_upload_params(arg) {
        return await axios({
            url: ChannelsApi.helper_upload_params,
            method: "post",
            data: {
                "timestamp": +new Date(),
                "_log_finder_uin": "",
                "_log_finder_id": arg._log_finder_id,
                "rawKeyBuff": null,
                "pluginSessionId": null,
                "scene": 7,
                "reqScene": 7
            },
            headers: {...this.headers, 'X-WECHAT-UIN': '0000000000', Cookie: arg.cookies,}
        })

    }

    /**
     * 初始化配置
     */
    async getConfigure(arg) {
        const Ffmpeg = new FfmpegAddon()
        const {chunks: videochunks, fileSize} = await this.readBigFile(arg.filePath)
        const helper_upload_params_response = await this.helper_upload_params(arg)
        const {fileJag, width, height, duration} = await Ffmpeg.coverAndduration(arg.filePath)
        if (helper_upload_params_response.data.errCode === 0) {
            Log.info("视频正在初始化");
            return {
                fileName: path.basename(arg.filePath),
                fileSize: fileSize,
                taskid: uuidv4(),
                videochunks: videochunks,
                appType: helper_upload_params_response.data.data.appType,
                authKey: helper_upload_params_response.data.data.authKey,
                uin: helper_upload_params_response.data.data.uin,
                videoFileType: helper_upload_params_response.data.data.videoFileType,
                pictureFileType: helper_upload_params_response.data.data.pictureFileType,
                fileJag, width, height,
                duration
            }
        }

        throw new Error("Cooike失效,请重新登入")

    }


    /**
     * 获取UploadID
     */
    async getUploadID(config, XArguments, fileSize) {
        const headers = {Authorization: config.authKey, 'x-Arguments': XArguments, ...this.headers}
        const data = {
            "BlockSum": Math.ceil(fileSize / 8388608),
            "BlockPartLength": (() => {
                const FileSub = 1024 * 1024 * 8;
                const BlockSum = Math.ceil(fileSize / FileSub);
                return new Array(BlockSum).fill(1).map((function (e, t) {
                        var n = (t + 1) * FileSub;
                        return n > fileSize ? fileSize : n
                    }
                ))
            })()
        }
        Log.info("视频正在获取uploadid");
        return await axios({
            url: ChannelsApi.applyuploaddfs,
            method: "put",
            data: data,
            headers: {...this.headers, ...headers}
        })
    }


    /**
     * 上传单分片
     */
    async uploadpartdfs(config, i, UploadID, XArguments, videochunks) {
        const headers = {
            "Content-Type": "application/octet-stream",
            "Content-Md5": null,
            "Authorization": config.authKey,
            "Content-Length": videochunks[i - 1].toString('binary').length,
            "X-Arguments": XArguments

        }
        return await axios({
            url: `${ChannelsApi.uploadpartdfs}PartNumber=${i}&UploadID=${UploadID}`,
            method: "PUT",
            headers: {...this.headers, ...headers},
            data: videochunks[i - 1]
        })
    }

    /**
     * 合并视频
     */
    async completepartuploaddfs(config, XArguments, UploadID, completepart) {
        const headers = {
            "authorization": config.authKey,
            "X-Arguments": XArguments,
            "content-md5": null,
            "content-length": JSON.stringify(completepart).length
        }
        return await axios({
            url: `${ChannelsApi.completepartuploaddfs}${UploadID}`,
            method: "post",
            headers: {...this.headers, ...headers},
            data: JSON.stringify(completepart)
        })

    }

    /**
     * 获取视频下载地址
     */
    async applyuploaddfs(config) {
        try {
            let XArguments = `apptype=${config.appType}&filetype=${config.videoFileType}&weixinnum=${config.uin}&filekey=temp.mp4&filesize=${config.fileSize}&taskid=${config.taskid}&scene=0`
            const Reponse_uoload = await this.getUploadID(config, XArguments, config.fileSize)
            let uploadCdnStart = + new Date() / 1000
            if (Reponse_uoload.data.UploadID) {
                const completepart = {TransFlag: "0_0", PartInfo: []}
                for (let i = 1; i <= config.videochunks.length; i++) {
                    const ETag = await this.uploadpartdfs(config, i, Reponse_uoload.data.UploadID, XArguments, config.videochunks)
                    Log.info(`TAG : ${ETag["data"]["ETag"]}`);
                    if (ETag["data"]["X-Errno"] === 0) {
                        completepart.PartInfo.push({PartNumber: i, ETag: ETag["data"]["ETag"]})
                    }
                }
                let uploadCdnEnd = +new Date() / 1000
                let completepart_response = await this.completepartuploaddfs(config, XArguments, Reponse_uoload.data.UploadID, completepart)
                const DownloadURL = completepart_response.data.DownloadURL
                if (DownloadURL) {
                    Log.info(`视频地址: ${DownloadURL}`);
                    return Object.assign(config, {uploadCdnStart}, {uploadCdnEnd}, {url: DownloadURL.replace('http://wxapp.tc.qq.com', 'https://finder.video.qq.com')})
                }
            }
            throw new Error("获取UploadID错误")
        } catch (err) {
            Log.info(err);
        }


    }

    /**
     * 获取图片下载地址
     */
    async applyuploaddfsJpg(config) {
        try {
            const {chunks: picturechunks, fileSize} = await this.readBigFile(config.fileJag)
            const jpgName = path.basename(config.fileJag)
            const XArguments = `apptype=${config.appType}&filetype=${config.pictureFileType}&weixinnum=${config.uin}&filekey=finder_video_img.jpeg&filesize=${fileSize}&taskid=${uuidv4()}&scene=0`
            const jpgUploadId_response = await this.getUploadID(config, XArguments, fileSize)
            if (jpgUploadId_response.data.UploadID) {
                const completepart = {TransFlag: "0_0", PartInfo: []}
                for (let i = 1; i <= picturechunks.length; i++) {
                    const ETag = await this.uploadpartdfs(config, i, jpgUploadId_response.data.UploadID, XArguments, picturechunks)
                    Log.info(`TAG : ${ETag["data"]["ETag"]}`);
                    if (ETag["data"]["X-Errno"] === 0) {
                        completepart.PartInfo.push({PartNumber: i, ETag: ETag["data"]["ETag"]})
                    }
                }
                let completepart_response = await this.completepartuploaddfs(config, XArguments, jpgUploadId_response.data.UploadID, completepart)
                const DownloadURL = completepart_response.data.DownloadURL
                if (DownloadURL) {
                    await this.remove_file(config.fileJag)
                    Log.info('remove fileJpg success')
                    Log.info(`图片地址: ${DownloadURL}`);
                    return Object.assign(config, {thumbUrl: DownloadURL.replace('http://wxapp.tc.qq.com', 'https://finder.video.qq.com')})
                }

            }
        } catch (err) {
            throw Error(err)
        }
    }

    /**
     * 解构描述
     */
    finderTopicInfo(description) {
        const desc = description.split(' ')
        let content = [`<finder><version>1</version><valuecount>${desc.length}</valuecount><style><at></at></style>`]
        for (let [index, item] of desc.entries()) {
            if (item.includes("#")) {
                content.push(`<value${index}><topic><![CDATA[${item}#]]></topic></value${index}>`)
            } else {
                content.push(`<value${index}><![CDATA[ ${item}]]></value${index}>`)
            }
        }
        content.push('</finder>')
        return content.join(' ');
    }


    /**
     * post_clip_video 剪切视频
     */

    async post_clip_video(config) {
        const data = {
            "url": config.url,
            "timeStart": 0,
            "cropDuration": 0,
            "height": config.height,
            "width": config.width,
            "x": 0,
            "y": 0,
            "clipOriginVideoInfo": {
                "width": config.width,
                "height": config.height,
                "duration": parseInt(config.duration, 10),
                "fileSize": config.fileSize
            },
            "traceInfo": {
                "traceKey": "",
                "uploadCdnStart": config.uploadCdnStart / 1000,
                "uploadCdnEnd": config.uploadCdnEnd  / 1000
            },
            "targetWidth": config.width,
            "targetHeight": config.height,
            "type": 4,
            "timestamp": +new Date(),
            "_log_finder_uin": config._log_finder_uin,
            "_log_finder_id": config._log_finder_id,
            "rawKeyBuff": null,
            "pluginSessionId": null,
            "scene": 7,
            "reqScene": 7
        }
        const headers = {
            "X-Wechat-Uin": config.uin,
            Cookie: config.cookies,
            Referer: "https://channels.weixin.qq.com/platform/post/create",
            Origin: "https://channels.weixin.qq.com"
        }
        const post_video_clip_response = await axios({
            url: ChannelsApi.post_clip_video,
            method: "post",
            data: data,
            headers: {...this.headers, ...headers},
        })
        if (post_video_clip_response.data.errCode === 0) {
            return Object.assign(config, post_video_clip_response.data.data)
        }
        throw Error("获取clipKey出错")
    }

    /**
     * 发布视频
     */
    async post_create(Config) {
        try {
            const data =
                {
                    "objectType": 0,
                    "longitude": 0,
                    "latitude": 0,
                    "feedLongitude": 0,
                    "feedLatitude": 0,
                    "originalFlag": 0,
                    "postFlag":0,
                    "topics": function extractTagsFromString(str) {
                        if (str && str.includes("#")) {
                            var regex = /#([\p{L}\p{N}_]+)/gu;
                            var matches = str.match(regex);
                            var tags = matches.map(function (match) {
                                return match.slice(1);
                            });
                        }
                        return tags;
                    }(Config.description),
                    "isFullPost": 1,
                    "handleFlag": 2,
                    "videoClipTaskId": Config.clipKey,
                    "traceInfo": {
                        "traceKey": "",
                        "uploadCdnStart": Config.uploadCdnStart,
                        "uploadCdnEnd": Config.uploadCdnEnd
                    },
                    "objectDesc": {
                        "mpTitle": "",
                        "description": Config.description,
                        "extReading": Config.link ? {
                            "link":Config.link,
                            "title":Config.title,
                            "urlType":Config.urlType
                        } : {},
                        "mediaType": 4,
                        "location": {},
                        "topic": {
                            "finderTopicInfo": function convertToXML(data) {
                                if(data){
                                    const tags = data.split(" ");
                                    let xml = "<finder><version>1</version><valuecount>" + tags.length + "</valuecount><style><at></at></style>";

                                    for (let i = 0; i < tags.length; i++) {
                                        xml += "<value" + i + "><topic><![CDATA[" + tags[i] + "#]]></topic></value" + i + ">";
                                    }

                                    xml += "</finder>";

                                    return xml;
                                }
                            }(Config.description)
                        },
                        "event": {},
                        "mentionedUser": [],
                        "media": [
                            {
                                "url": Config.url,
                                "fileSize": Config.fileSize,
                                "thumbUrl": Config.thumbUrl,
                                "fullThumbUrl": Config.thumbUrl,
                                "mediaType": 4,
                                "videoPlayLen": parseInt(Config.duration, 10),
                                "width": Config.width,
                                "height": Config.height,
                                "md5sum": uuidv4(),
                                "cardShowStyle": 2,
                                "urlCdnTaskId": Config.clipKey
                            }
                        ]
                    },
                    "report": {
                        "clipKey": Config.clipKey,
                        "draftId": Config.draftId,
                        "timestamp": +new Date(),
                        "_log_finder_uin": Config._log_finder_uin,
                        "_log_finder_id": Config._log_finder_id,
                        "rawKeyBuff": null,
                        "pluginSessionId": null,
                        "scene": 7,
                        "reqScene": 7,
                        "height": Config.height,
                        "width": Config.width,
                        "duration": parseInt(Config.duration, 10),
                        "fileSize": Config.fileSize,
                        "uploadCost": (Config.uploadCdnEnd - Config.uploadCdnStart) / 2
                    },
                    "mode": 1,
                    "clientid": uuidv4(),
                    "timestamp": +new Date(),
                    "_log_finder_uin": Config._log_finder_uin,
                    "_log_finder_id": Config._log_finder_id,
                    "rawKeyBuff": null,
                    "pluginSessionId": null,
                    "scene": 7,
                    "reqScene": 7,
                    "effectiveTime": Config.effectiveTime
                }
            const headers = {
                "X-Wechat-Uin": Config.uin,
                "Cookie": Config.cookies,
                Referer: "https://channels.weixin.qq.com/platform/login"
            }
            const post_video_clip_response = await axios({
                url: ChannelsApi.post_create,
                method: "post",
                data: data,
                headers: {...this.headers, ...headers},
            })
            return post_video_clip_response
        } catch (err) {
            throw new Error("发布失败")
        }
    }

    async switch_account(Config){
        const headers = {
            "X-Wechat-Uin": "0000000000",
            "Cookie": Config.cookies,
        }
        const data={
            "finderUsername": Config._log_finder_id,
            "timestamp": + new Date(),
            "_log_finder_id":Config._log_finder_id,
            "rawKeyBuff": "",
            "pluginSessionId": null,
            "scene": 1
        }
        const result =  await axios({
            url: ChannelsApi.auth_set_finder,
            method: "post",
            data: data,
            headers: {...this.headers, ...headers},
        })
        console.log(result.data)
    }


    //入口函数
    async SendChannelsVideo(args) {
        try {
            let cookies = this.resetCookie(args.cookies);
            args.cookies = cookies;
            if(args.url){
                const resLink = await this.getMpLinkData(args);
                if(resLink.data.errCode === 0){
                    args.title = resLink.data.data['title'];
                    args.urlType = resLink.data.data['linkType']
                }
            }
            //  //修改状态为发布中
            await this.updateStatus(args.id,2);
            //组装参数
            const Config = {...args, ...await this.getConfigure(args)}
            console.log(Config)
            await this.switch_account(Config)
            let videoData = await this.applyuploaddfs(Config)
            await this.applyuploaddfsJpg(Config)
            await this.post_clip_video(Config)
            await this.switch_account(Config)
            const postRes = await this.post_create(Config)
            let datas = Object.assign({},postRes,{coverLink:videoData.thumbUrl},{videoLink:videoData.url})
            Log.info(datas);
            return datas
        } catch (err) {
            Log.info(err);
        }
        return null
    }

    //
    // /**
    //  *
    //  * @param args
    //  * @returns {Promise<void>}
    //  */
    // async publishQueueByServer(args){
    //     let publishData = {};
    //     let that = this;
    //     let arg = {}  //上传参数
    //     //请求发布数据
    //    await  axios.get(request.getPublishData + args.username).then(async (res)=> {
    //        this.publishStatus = true;
    //         publishData = res['data']['data'];
    //        //判断是否返回数据
    //        if (publishData) {
    //            let isFolder = false;
    //            let filePath = '';
    //            if (publishData.filePath.indexOf(".mp4") !== -1) {
    //                filePath = publishData.filePath;
    //            } else {
    //                isFolder = true
    //                let mp4Path = this.getFileByMp4(publishData.filePath);
    //                //在这里写获取随机文件路径
    //                filePath = mp4Path
    //            }
    //             let cookie = this.resetCookie(publishData.cookies);
    //             arg.cookies = cookie;
    //             arg._log_finder_id = publishData.finderUserName;
    //             arg._log_finder_uin = publishData.uniqId;
    //             arg.filePath = filePath;
    //             arg.description = publishData.description;
    //             arg.link = publishData.link;
    //             arg.shortTitle = publishData.shortTitle;
    //             arg.mode = publishData.mode;
    //             arg.effectiveTime = publishData.effectiveTime;
    //
    //             //修改状态为发布中
    //             await this.publishErr(publishData.id,2);
    //             //发布视频
    //             let publishRes =  await this.SendChannelsVideo(arg);
    //             //发布成功后修改发布状态
    //             let resData = {
    //                 id:publishData.id,
    //                 status: publishRes.status === 0 ? 1 : -1,  //返回参数为0代表发布成功，否则为发布失败
    //                 resData:publishRes.message,
    //                 coverLink:publishRes.imgUrl,
    //                 videoLink:publishRes.videoUrl,
    //             }
    //             //删除对应视频
    //             if(isFolder){
    //                 fs.unlinkSync(filePath)
    //             }
    //             await  axios.post(request.updatePublishStatus ,resData).then(async (res)=>{
    //                 //发布下一个视频
    //                 setTimeout(()=>{
    //                     console.log("发布下一个视频！")
    //                     that.publishQueueByServer(args)
    //                 },3000)
    //             })
    //         }
    //     }).catch((err)=>{
    //        this.publishErr(publishData.id,-1);
    //         console.log(err)
    //     }).finally(()=>{
    //         this.publishStatus = false;
    //         Log.info('remove fileJpg success')
    //     })
    // }


    /**
     * 获取一个mp4文件
     * @param pathData
     * @returns {*|null}
     */
    getFileByMp4(pathData){
        let mp4Path = []
        fs.readdirSync(pathData).forEach((file)=>{
            const filePath = path.join(pathData,file);
            const stat = fs.statSync(filePath)
            if(stat.isFile() && path.extname(file).toLowerCase()===".mp4"){
                mp4Path.push(filePath)
            }
        })
        return mp4Path  &&  mp4Path[0]  ? mp4Path[0] :null;
    }


    /**
     * 获取请求cookie
     * @param cookies
     * @returns {string}
     */
    resetCookie(cookies){
        let ResCookie = ''
        let jsonCookie = JSON.parse(cookies);
        for (let i = 0 ; i < jsonCookie.length;i++) {
            if(jsonCookie[i].name === 'sessionid'){
                ResCookie =  'sessionid=' + jsonCookie[i].value;
            }
        }
        return ResCookie;
    }



    /**
     * 添加队列并执行
     */
    runTasks(args) {
        this.taskQueue.push(() => this.asyncTask(args, 1000));
    }


    /**
     * 队列任务执行器
     * @param args
     * @param delay
     * @returns {Promise<unknown>}
     */
    async asyncTask(args, delay) {
        return new Promise(resolve => {
            setTimeout(async () => {
                //返回参数
                let resData = {
                    id:args.id,
                    status: -1,  //-1代表失败
                    errMsg:undefined,
                    coverLink:undefined,
                    videoLink:undefined,
                }
                try {
                    const res = await this.SendChannelsVideo(args);
                    console.log(res);
                    if (res && res.data.errCode === 0) {
                        resData.status = 1;
                        resData.coverLink = res.coverLink;
                        resData.videoLink = res.videoLink;
                        this.updateData(resData);
                    } else {
                        resData.errMsg = res.data.errMsg;
                        this.updateData(resData);
                    }
                } catch (error) {
                    this.updateData(resData);
                    Log.error('An error occurred while executing the task:',error)
                }finally {
                    setTimeout(()=>{
                        Log.info("剩余队列任务数：" + this.taskQueue.queue.length)
                        resolve(true);
                    },args.outTime)
                }
            }, delay);
        });
    }


    /**
     * 修改发布状态接口
     */
    updateStatus(accountId,status){
        axios.post(request.updatePublishStatus ,{id:accountId,status:status}).then(async (res)=>{})
    }
    //修改数据
    updateData(resData){
        let param = {
            id:resData.id,
            status:resData.status,
            errLog:resData.errMsg,
            coverLink:resData.coverLink,
            videoLink:resData.videoLink
        }
        axios.post(request.updatePublishStatus ,param).then(async (res)=>{})
    }

    /**
     * 获取草稿箱列表
     */
    async getDraftList(Config){
       let cookies =   this.resetCookie(Config.cookies);
        const headers = {
            "X-Wechat-Uin": "0000000000",
            "Cookie": cookies,
        }
        const data = {
            "currentPage": 1,
            "pageSize": 20,
            "pluginSessionId":null,
            "rawKeyBuff": null,
            "reqScene": 7,
            "scene": 7,
            "timestamp": new Date(),
            "_log_finder_id": Config._log_finder_id,
            "_log_finder_uin": ""
        }
        return await axios({
            url: ChannelsApi.getDraftList,
            method: "post",
            data: data,
            headers: {...this.headers, ...headers},
        })
    }


    /**
     * 获取公众号链接
     * @param arg
     */
    async getMpLinkData(arg){
        return await axios({
            url: ChannelsApi.getMpLink,
            method: "post",
            data: {
                pluginSessionId:null,
                rawKeyBuff:null,
                reqScene:7,
                scene:7,
                timestamp: + new Date(),
                url:arg.link,
                _log_finder_id:arg._log_finder_id,
                _log_finder_uin:""
            },
            headers: {...this.headers, 'X-WECHAT-UIN': '0000000000', Cookie: arg.cookies,}
        })
    }

}

// 创建 AnotherClass 实例
// const mediaService = new MediaService();
// // 调用 runTasks 方法开始执行任务
// mediaService.runTasks();

MediaService.toString = () => '[class MediaService]';
module.exports = MediaService;